//
//  RMMAdressDetailsViewController.m
//  Romomo
//
//  Created by puman on 2017/1/6.
//  Copyright © 2017年 mazegong. All rights reserved.
//

#import "RMMAdressDetailsViewController.h"
#import "RMMAdressDetailsTableViewCell.h"

@interface RMMAdressDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, AMapSearchDelegate>

@property (strong, nonatomic) UIActivityIndicatorView *indicatorView;

@end

@implementation RMMAdressDetailsViewController
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    UITextField *_searchTextF;
    AMapSearchAPI *_search;
    UIBarButtonItem *_item;
    NSString *_latitude; //纬度
    NSString *_longitude; //经度
    UIView *_backView;
    NSArray *_locationArray;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"选择输入详细地址";
    self.view.backgroundColor = kCColor;
    [self addViews];
    // Do any additional setup after loading the view.
}
- (void)addViews{
    _searchTextF = [[UITextField alloc] initWithFrame:CGRectMake(kScreenWideth / 2 - 150, kRow, 300, 40)];
    _searchTextF.textAlignment = NSTextAlignmentCenter;
    _searchTextF.borderStyle = UITextBorderStyleRoundedRect;
    _searchTextF.delegate = self;
    _searchTextF.font = kFont(14);
    _searchTextF.placeholder = @"请输入你的地址";
    _searchTextF.text = _delAdress;
    _searchTextF.clearButtonMode = UITextFieldViewModeWhileEditing;
    TEXTFIELD_S(_searchTextF, textValueChanged:);
    if (_searchTextF.text.length) {
//        _search = [[AMapSearchAPI alloc] init];
//        _search.delegate = self;
//        AMapPOIKeywordsSearchRequest *keywordsRequest = [[AMapPOIKeywordsSearchRequest alloc] init];
//        keywordsRequest.city = _curruet_city;
//        keywordsRequest.keywords = _searchTextF.text;
//        keywordsRequest.requireExtension = YES;
//        [_search AMapPOIKeywordsSearch:keywordsRequest];
        [self getDetailsAdressDataWith:_searchTextF.text];
    }
    [self.view addSubview:_searchTextF];
    _dataArray = [NSMutableArray array];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _searchTextF.bottom + kRow, kScreenWideth, kScreenHeight - 64 - _searchTextF.bottom - kRow) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    [_tableView registerClass:[RMMAdressDetailsTableViewCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:_tableView];
    
    _item = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:(UIBarButtonItemStylePlain) target:self action:@selector(save)];
   // _item.tintColor = kBasicColor;
    
    _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _backView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    _backView.hidden = YES;
    [self.view addSubview:_backView];

    _indicatorView = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(kScreenWideth / 2 - 50, 200, 100, 100)];
    _indicatorView.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [_indicatorView startAnimating];
    [_backView addSubview:_indicatorView];
}
- (void)save{
    if (!_latitude.length) {
        NSDictionary *dic = _locationArray[0];
        NSDictionary *locationDic = dic[@"location"];
        _latitude = [NSString stringWithFormat:@"%.6f",[locationDic[@"lat"] floatValue]];
        _longitude = [NSString stringWithFormat:@"%.6f",[locationDic[@"lng"] floatValue]];
        _searchTextF.text =  [NSString stringWithFormat:@"%@",dic[@"name"]];
    }
    _blockTude(_latitude,_longitude,_searchTextF.text);
    [self.navigationController popViewControllerAnimated:YES];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _locationArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  //  AMapPOI *tip = _dataArray[indexPath.row];
    return 60;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RMMAdressDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
//    AMapTip *tip = _dataArray[indexPath.row];
//    cell.titleLabel.text =  [NSString stringWithFormat:@"%@",tip.name];
//    cell.contentLabel.text = [NSString stringWithFormat:@"%@%@",tip.district,tip.address];
//    AMapTip *newTip = _dataArray[0];
//    _latitude = [NSString stringWithFormat:@"%.6f",newTip.location.latitude];
//    _longitude = [NSString stringWithFormat:@"%.6f",newTip.location.longitude];
    NSDictionary *dic = _locationArray[indexPath.row];
    cell.titleLabel.text   = [NSString stringWithFormat:@"%@",dic[@"district"]];
    cell.contentLabel.text = [NSString stringWithFormat:@"%@",dic[@"name"]];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [_searchTextF resignFirstResponder];
//    AMapTip *tip = _dataArray[indexPath.row];
//    _searchTextF.text =  [NSString stringWithFormat:@"%@",tip.name];
//    _latitude = [NSString stringWithFormat:@"%.6f",tip.location.latitude];
//    _longitude = [NSString stringWithFormat:@"%.6f",tip.location.longitude];
    NSDictionary *dic = _locationArray[indexPath.row];
    if (![dic[@"location"] isKindOfClass:[NSDictionary class]]) {
        [RMMFileManager MBProgressWith:@"请输入详细的地址!" onView:self.view];
        return;
    }
    self.navigationItem.rightBarButtonItem = _item;
    NSDictionary *locationDic = dic[@"location"];
    _latitude = [NSString stringWithFormat:@"%.6f",[locationDic[@"lat"] floatValue]];
    _longitude = [NSString stringWithFormat:@"%.6f",[locationDic[@"lng"] floatValue]];
    _searchTextF.text =  [NSString stringWithFormat:@"%@",dic[@"name"]];

    if (_delAdress.length) {
        if (![_delAdress isEqualToString:dic[@"name"]]) {
            self.navigationItem.rightBarButtonItem = _item;
        }
    }

}
- (void)textValueChanged:(UITextField *)textF{
    self.navigationItem.rightBarButtonItem = nil;
    if (textF.text.length >= 2) {
        [self getDetailsAdressDataWith:textF.text];
    }
//    if (_backView.hidden) {
//        _backView.hidden = NO;
//    }
    
//    _search = [[AMapSearchAPI alloc] init];
//    _search.delegate = self;
//    AMapPOIKeywordsSearchRequest *keywordsRequest = [[AMapPOIKeywordsSearchRequest alloc] init];
//    keywordsRequest.city = _curruet_city;
//    keywordsRequest.keywords = textF.text;
//    keywordsRequest.requireExtension = YES;
//    [_search AMapPOIKeywordsSearch:keywordsRequest];
}
- (void)getDetailsAdressDataWith:(NSString *)details{
    NSString *timersTemp = [RMMFileManager getTimesTamp];
    NSString *sign = [RMMFileManager getMD5WithString:timersTemp];
    NSString *url = [NSString stringWithFormat:@"%@%@",kBaseUrl,GetDetailAdressUrl];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"timestamp"]       = timersTemp;
    parDic[@"appid"]           = APPID;
    parDic[@"sign"]            = sign;
    parDic[@"CityName"]        = _curruet_city;
    parDic[@"AddressDetail"]   = details;
    [OSRequestManager requestNoProgressWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            _locationArray = dataDic[@"data"];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
        [_tableView reloadData];
    } error:^(NSError *errors) {
        
    } view:self.view];
}
// 代理方法
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response{
    if (response.pois.count == 0) {
        return;
    }
    if (!_backView.hidden) {
        _backView.hidden = YES;
    }
    [_dataArray removeAllObjects];
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.address.length > 0) {
            [_dataArray addObject:obj];
        }
    }];
    [_tableView reloadData];
}
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0)
    {
        return;
    }
    for ( int num = 0; num < response.tips.count;  num ++) {
        _dataArray = [NSMutableArray arrayWithArray: response.tips];
    }
    [_tableView reloadData];
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %ld", response.count];
    NSString *strtips = @"";
    for (AMapTip *p in response.tips) {
        strtips = [NSString stringWithFormat:@"%@\nTip: %@", strtips, p.description];
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@", strCount, strtips];
    NSLog(@"InputTips: %@", result);
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
